package querysrc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.subway.babynote.syncdata.*;





public class query_RegVisitor extends query {
	
	public query_RegVisitor(sqlConnectionHandler sqlconhandler)
	{
		super(sqlconhandler);
	}
	//return visitor_id
	public int Register(ClientDataRecord.visitorRecord vr)
	{
		ResultSet rs = null;
		querydb qdb = null;
		int iret = -1;
		Connection con = null;
		try
		{
			boolean bret = true;
			con = this.init();	
			if(bret)
			{
				qdb = new querydb(con, sqlscripts.sql_reg_visitor_select_v_uid);
				bret = qdb.prePS();				
			}
			if(bret)
			{
				qdb.ps.setString(1, vr.imsi);
				qdb.ps.setString(2, vr.imei);
				rs = qdb.execPSQuery();
				if (!rs.next()){
					//new visitor
					iret = IdManager.user_id.getnewid();
					vr.visitor_id = iret;
					//insert
					this.insertvisitorinfo(con,vr);			        
			      }
			      else {    	 
			    	  iret = rs.getInt(sqlscripts.sql_reg_visitor_select_v_uid_c1);			        
			        }
				
				return iret;
			}
			return -1;
			
		}
		catch(SQLException se) {
		      System.out.println("SQLException: "+se.getMessage());
		      return -1;
	    }
		catch(Exception e)
		{
			e.printStackTrace();
			return -1;
		}
		finally
		{
			this.release_resultset(rs);
			this.release_querydb(qdb);
			this.release_connection(con);
			this.finalize();
		}
	}
	
	private int insertvisitorinfo(Connection con ,ClientDataRecord.visitorRecord vr)
	{
		//(visitor_id,imsi,imei,phone_number,first_use_time, birth, gender)
		querydb qdb = null;
		try
		{
			boolean bret = true;
			int iret = -1;
			qdb = new querydb(con,sqlscripts.sql_reg_visitor_insert);
			bret = qdb.prePS();
			if(bret)
			{
				qdb.ps.setInt(1, vr.visitor_id);
				qdb.ps.setString(2, vr.imsi);
				qdb.ps.setString(3,vr.imei);
				qdb.ps.setString(4, vr.phone_number);
				qdb.ps.setString(5, StringUtil.date2str(vr.first_use_time));
				qdb.ps.setDate(6, vr.birth);
				qdb.ps.setBoolean(7, vr.gender);
				iret = qdb.execPSInsert();				
			}				
			return iret;			
		}
		catch(SQLException se) {
		      System.out.println("SQLException: "+se.getMessage());
		      return -1;
	    }
		catch(Exception e)
		{
			e.printStackTrace();
			return -1;
		}
		finally
		{
			this.release_querydb(qdb);
		}
	}
	

}
